<template>
  <div class="make-order-container"
       v-if="store_final_total_list">

    <!-- 收货地址 -->
    <div class="address-info flex order-ma-top align-center"
         @click="goAddress">
      <img class="address-icon"
           src="@/assets/image/address-icon.png" />
      <div class="info flex-sub"
           v-if="store_final_total_list.address_info">
        <div class="user-info">
          <span>{{store_final_total_list.address_info.address_realname}}</span>
          <span>{{store_final_total_list.address_info.address_mob_phone}}</span>
        </div>
        <div class="address-detail">{{store_final_total_list.address_info.area_info}}{{store_final_total_list.address_info.address_detail || ''}}</div>
      </div>
      <div class="add-address flex-sub"
           v-else>
        您还没有收货地址，点击这里添加。
      </div>
      <van-icon name="arrow"
                class="right-icon" />
    </div>

    <!-- 订单列表 -->
    <template v-for="(store,store_index) in store_final_total_list.store_cart_list">
      <div class="store-order order-ma-top"
           :key="'goods_info_'+store_index">
        <div class="store-info flex align-center">
          <van-icon class="store-icon"
                    name="shop-o" />
          <div>{{store.store_name}}</div>
        </div>
        <div class="goods-list">
          <!-- 商品信息 -->
          <goods-module module-name="goods1n"
                        goodsImg="goods_image_url"
                        goodsName="goods_name"
                        goodsPrice="goods_price"
                        goodsId="goods_id"
                        goodsNum="goods_num"
                        :list="store.goods_list"
                        @clickGoods="clickGoods">
          </goods-module>
        </div>
      </div>
      <div class="store-order order-ma-top"
           :key="'order_info_'+store_index">
        <!-- 订单信息 -->
        <div class="menu-list">
          <div class="menu-item">
            <div class="label">商品总额</div>
            <div class="content text-right">
              <span class="text-price">{{store.store_goods_total}}</span>
            </div>
          </div>
          <div class="menu-item">
            <div class="label">运费</div>
            <div class="content text-right">
              <span class="text-price"
                    v-if="store_final_total_list.address_api">{{store_final_total_list.address_api.content[store.store_id]}}</span>
              <span class="text-price"
                    v-else>0.00</span>
            </div>
          </div>
          <div class="menu-item">
            <div class="label">备注</div>
            <div class="content">
              <van-field v-model="message[store.store_id]"
                         rows="1"
                         autosize
                         type="textarea"
                         placeholder="请输入留言" />
            </div>
          </div>
          <div class="menu-item">
            <div class="content text-right">
              <span>小计：</span>
              <span class="text-price main-color">{{store_final_total_list.store_final_total_list[store.store_id]}}</span>
            </div>
          </div>
        </div>
      </div>
    </template>

    <!-- 订单底部 -->
    <div class="footer">
      <div class="fixed-footer flex">
        <div class="price-info flex-sub flex align-baseline">
          <van-switch-cell v-model="pd_pay"
                           active-color="#E9AC64"
                           title="余额支付"
                           class="switch-padding-0"
                           v-if="showPdPay"
                           :disabled="mustPdPay" />
          <span>合计：</span>
          <span class="text-price price">{{store_final_total_list.order_amount}}</span>
        </div>
        <van-button class="submit-btn"
                    @click.stop="checkout">去结算</van-button>
      </div>
    </div>

    <pay-panel v-model="showPayPanel"
               @pswCallback="pswCallback"></pay-panel>
  </div>
</template>

<script>
import { buyStep1, buyStep2, checkFCode } from '@/api/makeOrder'
import GoodsModule from '@/components/GoodsModule'
import { mapMutations } from 'vuex'
import { Dialog, Toast } from 'vant'
import PayPanel from '@/components/PayPanel'
export default {
  name: 'MakeOrder',
  components: {
    GoodsModule,
    PayPanel
  },
  data() {
    return {
      pay_code: 'online',
      mustPdPay: false, // 强制余额支付
      f_code: '',
      invoice_id: this.$route.query.invoice_id
        ? this.$route.query.invoice_id
        : 0,
      invoice_content: this.$route.query.invoice_content
        ? this.$route.query.invoice_content
        : '',
      f_code_check: false,
      cart_id: this.$route.query.cart_id ? this.$route.query.cart_id : '',
      store_final_total_list: null,
      pd_pay: false,
      rcb_pay: false,
      password: '',
      message: [],
      share_uid: '', // 分享者ID
      showPayPanel: false, // 显示输入密码弹窗
      shareCode: this.$route.query.shareCode || null // 分享人ID
    }
  },
  created: function() {
    this.getBuyInfo()
  },
  computed: {
    /**
     * 是否显示余额支付
     */
    showPdPay() {
      // 先判断有没有订单信息
      if (this.store_final_total_list) {
        // 该对象为数组的时候余额为0
        if (this.store_final_total_list.available_predeposit instanceof Array) {
          // 余额为0、如果订单金额也小于0.那就还是显示按钮
          return Number(this.store_final_total_list.order_amount) <= 0
        } else {
          return (
            Number(this.store_final_total_list.available_predeposit) >=
            Number(this.store_final_total_list.order_amount)
          )
        }
      }
      return false
    }
  },
  methods: {
    ...mapMutations({
      memberInviterId: 'memberInviterId'
    }),

    checkfcode() {
      checkFCode(
        this.store_final_total_list.store_cart_list_api[0].goods_list[0]
          .goods_commonid,
        this.f_code
      )
        .then(res => {
          this.f_code_check = true
        })
        .catch(error => {
          this.$toast({
            type: 'fail',
            message: error.message
          })
        })
    },
    // 获取订单信息
    getBuyInfo() {
      let extra = {}
      if (this.$route.query.bargainorder_id) {
        extra['bargainorder_id'] = this.$route.query.bargainorder_id
      }
      buyStep1(
        this.cart_id,
        this.$route.query.buy_now ? 0 : 1,
        this.$route.query.pintuan_id,
        this.$route.query.pintuangroup_id,
        extra
      )
        .then(res => {
          this.store_final_total_list = res.result

          // 如果是领取小礼品，订单金额为0.强制余额支付
          if (parseFloat(this.store_final_total_list.order_amount) === 0) {
            this.pd_pay = true
            this.mustPdPay = true // 强制余额支付
          }
          if (this.invoice_content) {
            if (!this.store_final_total_list.inv_info.invoice_id) {
              this.invoice_id = 0
              this.invoice_content = this.store_final_total_list.inv_info.content
            }
          } else {
            this.invoice_content = this.store_final_total_list.inv_info.content
            if (this.store_final_total_list.inv_info.invoice_id) {
              this.invoice_id = this.store_final_total_list.inv_info.invoice_id
            }
          }
        })
        .catch(error => {
          this.$toast({
            type: 'fail',
            message: error.message
          })
        })
    },
    goAddress() {
      if (this.store_final_total_list.address_info) {
        this.$router.push({ name: 'AddressList' })
      } else {
        this.$router.push({
          name: 'AddressForm',
          query: {
            action: 'add',
            isFromCheckout: true,
            goBackLevel: -1
          }
        })
      }
    },

    /**
     * 输入支付密码后的回调
     */
    pswCallback(psw) {
      this.password = psw
      this.checkout() // 重新拉起支付
    },

    // 提交订单
    checkout() {
      let ifcart = this.$route.query.buy_now ? 0 : 1
      let pintuanId = this.$route.query.pintuan_id
      let pintuangroupId = this.$route.query.pintuangroup_id
      let cartId = this.cart_id
      let addressId = this.store_final_total_list.address_info
        ? this.store_final_total_list.address_info.address_id
        : 0
      let vatHash = this.store_final_total_list.vat_hash
      let offpayHash = this.store_final_total_list.address_api.offpay_hash
      let offpayHashBatch = this.store_final_total_list.address_api
        .offpay_hash_batch
      let invoiceId = this.invoice_id
      let voucher = null
      let pdPay = this.pd_pay ? 1 : 0
      let password = this.password
      let rcbPay = this.rcb_pay ? 1 : 0
      let payMessageTemp = []
      let fCode = this.f_code
      let payCode = this.pay_code
      if (!addressId) {
        this.$toast({
          type: 'fail',
          message: '您需要先去添加收货地址'
        })
        return
      }
      if (pdPay || rcbPay) {
        if (!this.store_final_total_list.member_paypwd) {
          Dialog.confirm({
            title: '提示',
            message: '您需要先去设置支付密码'
          })
            .then(() => {
              this.$router.push({ name: 'EditPayPassword' })
            })
            .catch(res => {})
          return false
        } else {
          if (!password) {
            // 打开支付密码弹窗
            this.showPayPanel = true
            return false
          }
        }
      }
      // 处理格式
      voucher = ''
      let voucherTemp = []
      for (var t in this.store_final_total_list.store_cart_list) {
        voucherTemp.push([
          this.store_final_total_list.store_cart_list[t].store_voucher_info
            .vouchertemplate_id +
            '|' +
            t +
            '|' +
            this.store_final_total_list.store_cart_list[t].store_voucher_info
              .voucher_price
        ])
      }
      voucher = voucherTemp.join(',')
      let i
      for (i in this.store_final_total_list.store_cart_list) {
        let storeId = this.store_final_total_list.store_cart_list[i].store_id
        let message = this.message[storeId]
        if (typeof message === 'undefined') {
          message = ''
        }
        payMessageTemp.push(
          this.store_final_total_list.store_cart_list[i].store_id +
            '|' +
            message
        )
      }
      let payMessage = payMessageTemp.join(',')
      let extra = {}
      if (this.$route.query.bargainorder_id) {
        extra['bargainorder_id'] = this.$route.query.bargainorder_id
      }

      this.$toast({
        type: 'loading',
        message: '加载中...',
        duration: 0,
        forbidClick: true,
        overlay: true
      })
      // extra['share_uid'] = this.share_uid // 分享人ID
      buyStep2(
        ifcart,
        cartId,
        addressId,
        vatHash,
        offpayHash,
        offpayHashBatch,
        invoiceId,
        voucher,
        pdPay,
        password,
        rcbPay,
        payMessage,
        pintuanId,
        pintuangroupId,
        fCode,
        payCode,
        this.shareCode,
        extra
      )
        .then(res => {
          // 跳转到支付界面
          let paySn = res.result.pay_sn
          this.$router.push({
            name: 'PayPage',
            query: { pay_sn: paySn, pay_type: 'pay_new' }
          })
          // 对接蜂鸟微信支付
          // this.$router.push({
          //   name: 'PayPage',
          //   query: { paySrc: encodeURI(res.result.go_url) }
          // })
          Toast.clear()
        })
        .catch(error => {
          Toast.clear()
          // 没有绑定微信的时候的
          if (error.code === 10010) {
            this.$toast({
              type: 'loading',
              message: error.message,
              duration: 3000,
              onClose: () => {
                this.$router.push({
                  name: 'BindWx',
                  query: { backUrl: window.location.href, type: 1 }
                })
              }
            })
          } else {
            this.$toast({
              type: 'fail',
              message: error.message
            })
          }
        })

      this.password = '' // 清空密码。下次重新输入
    },

    /**
     * 点击商品
     */
    clickGoods(info) {
      this.$router.push({
        name: 'Goodsdetail',
        query: { goods_id: info.goods_id }
      })
    }
  }
}
</script>

<style lang="scss">
.make-order-container {
  padding: 0 10px;
  .main-color {
    color: $mainColor;
  }

  .order-ma-top {
    margin-top: 10px;
  }

  // 地址模块
  .address-info {
    width: 100%;
    border-radius: 8px;
    background-color: #ffffff;
    padding: 15px 10px;
    .address-icon {
      width: 18px;
      height: 18px;
      align-self: flex-start;
    }
    .add-address {
      margin-left: 10px;
      color: #333333;
      font-size: 12px;
    }
    .info {
      margin-left: 10px;
      width: 250px;
      .user-info {
        color: #333333;
        font-size: 14px;
        font-weight: 550;
        margin-bottom: 10px;
        span {
          margin-right: 5px;
        }
      }
      .address-detail {
        width: 80%;
        color: #666666;
        font-size: 14px;
      }
    }
    .right-icon {
      font-size: 16px;
      color: #666666;
    }
  }

  .store-order {
    background-color: #ffffff;
    width: 100%;
    padding: 0 10px;
    border-radius: 8px;
    .store-info {
      height: 40px;
      position: relative;
      color: #333333;
      font-size: 14px;
      .store-icon {
        font-size: 14px;
        color: #333333;
        margin-right: 8px;
      }
      &::after {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 1px;
        background-color: #e5e5e5;
        transform: scaleY(0.5);
        content: '';
      }
    }

    .goods-list {
      &/deep/ .goods-1n-img {
        width: 75px;
        height: 75px;
      }
    }

    .menu-list {
      width: 100%;
      .menu-item {
        position: relative;
        min-height: 40px;
        line-height: 40px;
        display: flex;
        justify-content: space-between;
        .label {
          color: #666666;
          font-size: 13px;
        }
        .content {
          color: #333333;
          font-size: 14px;
          flex: 1;
          margin-left: 10px;
          &.text-right {
            text-align: right;
          }
        }
        &::after {
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          height: 1px;
          background-color: #e5e5e5;
          transform: scaleY(0.5);
          content: '';
        }
      }
    }
  }

  .footer {
    height: 80px;
    .fixed-footer {
      position: fixed;
      bottom: 0;
      left: 0;
      height: 50px;
      background-color: #ffffff;
      width: 100%;
      border-top: 1px solid #eeeeee;

      .price-info {
        padding: 0 3px;
        line-height: 50px;
        color: $mainColor;
        font-size: 13px;
        flex-wrap: wrap;
        margin-left: 10px;
        .switch-padding-0 {
          padding: 0;
          justify-content: flex-start;
          width: 115px;
        }
        .price {
          font-size: 18px;
        }
      }

      .submit-btn {
        width: 120px;
        height: 50px;
        line-height: 50px;
        background-color: $mainColor;
        color: #ffffff;
        font-size: 16px;
        margin-top: 0;
      }
    }
  }
}
</style>
